package com.hxh.generater.springBoot.springboot3_vue3.gen;

import com.hxh.config.Constants;
import com.hxh.entity.Project;
import com.hxh.util.GenUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

public class GenSb3Vue3Addition {
    public static void processDynamicDatasourceMaven(Project project) {
        String redisDependency =
                "      <dependency>\n" +
                "            <groupId>com.baomidou</groupId>\n" +
                "            <artifactId>dynamic-datasource-spring-boot3-starter</artifactId>\n" +
                "            <version>4.3.1</version>\n" +
                "        </dependency>";
        processMaven(project, redisDependency);

    }

    public static void processRedisMaven(Project project) {
        String redisDependency = "      <dependency>\n" +
                "            <groupId>org.redisson</groupId>\n" +
                "            <artifactId>redisson-spring-boot-starter</artifactId>\n" +
                "            <version>3.24.3</version>\n" +
                "        </dependency>\n";
        processMaven(project, redisDependency);

    }

    public static void processMongoMaven(Project project) {
        String mongoDependency = "        <dependency>\n" +
                "            <groupId>org.springframework.boot</groupId>\n" +
                "            <artifactId>spring-boot-starter-data-mongodb</artifactId>\n" +
                "        </dependency>\n";
        processMaven(project, mongoDependency);

    }

    private static void processMaven(Project project, String dependency) {
        String replaceWord = "<!--AUTO_INSERT_HERE-->";
        dependency = replaceWord + "\n" + dependency;

        try {
            File pomFile = GenUtil.newFile(project, "pom", "pom");
            FileWriter fileWriter = new FileWriter(pomFile);
            BufferedWriter writer = new BufferedWriter(fileWriter);

            String path = project.getBackendProject().getProjectDir() + project.getBackendProject().getProjectName() + File.separator + "pom.xml";
            File template = new File(path + ".bak");

            BufferedReader br = new BufferedReader(new FileReader(template));
            String line;
            while ((line = br.readLine()) != null) {
                if (StringUtils.isNotBlank(line)) {
                    line = line.replaceAll("#GroupId#", project.getBackendProject().getProjectGroup());
                    line = line.replaceAll("#ArtifactId#", project.getBackendProject().getProjectName());
                    line = line.replace(replaceWord, dependency);
                }
                if (StringUtils.isBlank(line)) {
                    writer.newLine();
                } else {
                    writer.write(line);
                    writer.newLine();
                }
            }
            br.close();
            writer.close();
            fileWriter.close();

        } catch (IOException e) {
            System.err.println("Failed to generate pom.xml: " + e.getMessage());
        }

    }

    public static void generationRedisCacheClass(Project project) {
        replaceDirectoryForComponent("", project, "_Redis");
    }

    public static void generationMongoCacheClass(Project project) {
        replaceDirectoryForComponent("", project, "_Mongo");
    }

    /**
     * 替换文件夹内所有文件的GroupId，按照文件夹内的相对目录，在对应的项目的相对路径中创建对应文件
     *
     * @param templateDirPath 文件夹
     * @param project         项目
     */
    public static void replaceDirectoryForComponent(String templateDirPath, Project project, String type) {
        File file = new File(GenSb3Vue3Util.FILE_PATH_PRE + templateDirPath);
        if (!file.exists()) {
            throw new RuntimeException("初始化" + templateDirPath + "异常!");
        }
        File[] files = file.listFiles();
        if (files == null) {
            return;
        }
        for (File file1 : files) {
            if (file1.isDirectory()) {
                replaceDirectoryForComponent(templateDirPath + "\\" + file1.getName(), project, type);
                continue;
            }
            String fileName = file1.getName();
            if (!fileName.endsWith(type)) {
                continue;
            }


            String filePath = file1.getPath();
            filePath = filePath.replace(GenSb3Vue3Util.FILE_PATH_PRE, "");
            String classFilePathPrefix = filePath.substring(0, filePath.length() - fileName.length() - 1);
            fileName = fileName.replace(type, "");
            ReplaceGroupIdUtil.replaceUtil(filePath, classFilePathPrefix, fileName, project);
        }
    }


    public static void generationApplicationDevYmlForRedis(Project project) {
        // 定义文件路径
        String filePath = GenSb3Vue3Util.FILE_PATH_PRE + "resources\\config\\redisConfig";

        // 使用 try-with-resources 自动管理 BufferedReader 的生命周期
        try (BufferedReader redisConfigBr = Files.newBufferedReader(Paths.get(filePath))) {
            StringBuilder sb = new StringBuilder();
            String templine;
            while ((templine = redisConfigBr.readLine()) != null) {
                if (StringUtils.isNotBlank(templine)) {
                    sb.append(templine);
                }
                sb.append("\n");
            }
            generationApplicationDBYmlForComponent(project, "#REDIS_CONFIG#", sb.toString());
        } catch (IOException e) {
            // 处理可能发生的 IO 异常
            e.printStackTrace();
        }
    }

    public static void generationApplicationDevYmlForMongo(Project project) {
        // 定义文件路径
        String filePath = GenSb3Vue3Util.FILE_PATH_PRE + "resources\\config\\mongoConfig";

        // 使用 try-with-resources 自动管理 BufferedReader 的生命周期
        try (BufferedReader redisConfigBr = Files.newBufferedReader(Paths.get(filePath))) {
            StringBuilder sb = new StringBuilder();
            String templine;
            while ((templine = redisConfigBr.readLine()) != null) {
                if (StringUtils.isNotBlank(templine)) {
                    sb.append(templine);
                }
                sb.append("\n");
            }
            generationApplicationDBYmlForComponent(project, "#MONGODB_CONFIG#", sb.toString());
        } catch (IOException e) {
            // 处理可能发生的 IO 异常
            e.printStackTrace();
        }
    }

    private static void generationApplicationDBYmlForComponent(Project project, String replaceKey, String replaceValue) {
        try {
            File classFile = GenUtil.newFile(project, "applicationConfig", "application-db");
            Map<String, String> genDatasourceConfig = GenSb3Vue3SystemBase.genDatasourceConfig(project);
            String datasourceConfig = genDatasourceConfig.get("datasourceConfig");
            String mutiDatasourceConfig = genDatasourceConfig.get("mutilDatasourceConfig");
            // 使用 try-with-resources 保证资源自动关闭
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(classFile))) {

                String resourcesPre = Constants.ProjectDirSuffix.substring(0, Constants.ProjectDirSuffix.lastIndexOf(File.separator));
                String path = project.getBackendProject().getProjectDir() + project.getBackendProject().getProjectName() + File.separator + resourcesPre + "\\resources\\config\\application-db.yml.bak";
                File template = new File(path);
                try (BufferedReader br = new BufferedReader(new FileReader(template))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        if (StringUtils.isNotBlank(line)) {
                            line = line.replaceAll("#DATASOURCE_CONFIG#", datasourceConfig);
                            line = line.replaceAll("#MUTIL_DATASOURCE_CONFIG#", mutiDatasourceConfig);
                            line = line.replaceAll(replaceKey, replaceValue);
                            writer.write(line);
                        }
                        writer.newLine();
                    }
                }
            }
        } catch (IOException e) {
            // 更详细的错误信息
            System.err.println("Failed to generate application-db.yml: " + e.getMessage());
        }
    }
}
